package dk.modified.reshary;

import java.util.Map;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class ResharyRestClient {

	private static final String BASE_URL = "/app_access/";
	
	private static AsyncHttpClient client = new AsyncHttpClient();

	public static void get(String url, RequestParams params,
			AsyncHttpResponseHandler responseHandler, Context c) {
		client.setUserAgent("reshary.com KBJdfbkjf88jkb Agent " + getVersion(c));
		client.get(getAbsoluteUrl(url,c), params, responseHandler);

	}

	public static void downloadImage(String url, RequestParams params,
			BinaryHttpResponseHandler responseHandler, Context c, Map<String, String> response) {
		client.setUserAgent("reshary.com KBJdfbkjf88jkb Agent " + getVersion(c));
		client.get(url, params, responseHandler);
	}

	public static void post(String url, RequestParams params,
			AsyncHttpResponseHandler responseHandler, Context c) {
		client.setUserAgent("reshary.com KBJdfbkjf88jkb Agent " + getVersion(c));
		client.post(getAbsoluteUrl(url,c), params, responseHandler);
	}
	
	public static void post_comment(String url, RequestParams params,
			AsyncHttpResponseHandler responseHandler, Context c) {
		client.setUserAgent("reshary.com KBJdfbkjf88jkb Agent " + getVersion(c));
		client.post(getAbsoluteUrl_comment(url,c), params, responseHandler);
	}

	private static String getAbsoluteUrl(String relativeUrl, Context c) {
		return c.getString(R.string.app_domain) + BASE_URL + relativeUrl;
	}
	
	private static String getAbsoluteUrl_comment(String relativeUrl, Context c) {
		return c.getString(R.string.app_domain) + "/" + relativeUrl;
	}

	private static String getVersion(Context c) {
		PackageInfo pInfo = null;
		try {
			pInfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
		} catch (NameNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return pInfo.versionName;

	}
}
